﻿package hapi.mvc.action;
import hapi.mvc.TemplateProvider;

class ShowAction<T> implements Action {

	var templateProvider:TemplateProvider;
	var finder:Int -> T;
	
	public function new(finder) {
		this.finder = finder;
	}
	
	public function run(params) {
		try {
			var object:T  = finder(params.id);
			displayContent(object);
		}catch (FindException e) {
			new ExceptionAction(e).run(params);
		}
	}
	
	function createView(name):TemplateView {
		var view =  hapi.log.DebugProxy.create(new TemplateView(getTemplateProvider(), name));
		return view;
	}
	
	function contentNotFound(?msg) { 
		var view = createView("errors/404");
		if(msg != null) view.assign("message", msg);
		view.display();
	}
	
	function displayContent(content:Displayable) {
		var templateName = "";
		var view = createView(templateName);
		view.assignDisplayable(content);
		view.display();
	}
	
	function getTemplateProvider():TemplateProvider {
		return templateProvider;
	}
	
	function getRequestParam(param:String) {
		return Web.getParams().get(param);
	}
	
	function forward(action:Class<Action>, ?params:Dynamic=null) {
		var uri = routeResolver.to(action, params);
		forwardToUri(uri);
	}
	
	function backToReferer() {
		var ref = Web.getClientHeader("Referer");
		if ( ref.indexOf("http") >= 0 )
			Web.redirect(ref);
		else
			forwardToUri(ref);
	}
	
	function forwardToUri(uri:String) {
		var host = Web.getClientHeader("Host");
		var url = "http://" + host +"" + uri;
		Web.redirect(url);
	}
}